package com.my.sender;

import com.my.pojo.Goods;
import com.my.pojo.Stock;
import com.my.service.IStockService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
@RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(value = "${mq.config.queue.stock.push}", autoDelete = "true"),
                exchange = @Exchange(value = "${mq.config.stock.exchange}", type = ExchangeTypes.FANOUT)
        )
)
public class InStockSender {

    IStockService stockService;

    @Autowired
    public void setStockService(IStockService stockService) {
        this.stockService = stockService;
    }

    @RabbitHandler
    public void process(String json) {
        System.out.println(json);
        try {
            JSONObject jsonObject = new JSONObject(json);
            Stock stock = new Stock();
            int num = jsonObject.getInt("num");
            if (num > 0) {
                stock.setType(1);
                stock.setNum(num);
            } else if (num < 0) {
                stock.setType(0);
                stock.setNum(-num);
            }
            Goods goods = new Goods();
            goods.setGoodsId(jsonObject.getInt("goods_id"));
            stock.setGoods(goods);
            stock.setInfo(jsonObject.getString("msg"));
            stock.setStatus(0);
            stock.setDate(new Date());
            this.stockService.in(stock);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
